﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace ShredTheLog.Converters
{
    [ValueConversion(typeof(int?), typeof(string))]
    public sealed class NullableIntConverter : ConverterBase, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var v = (int?)value;
            return v.HasValue ? v.Value.ToString(culture) : String.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var v = (string)value;
            int result;
            if (!String.IsNullOrWhiteSpace(v) && Int32.TryParse(v, out result))
                return (int?)result;
            else
                return (int?)null;
        }

        public static readonly NullableIntConverter Default = new NullableIntConverter();
    }
}
